//
//  ReactionViewController.m
//  autostainer
//
//  Created by lurenjia on 2017/5/25.
//  Copyright © 2017年 walker. All rights reserved.
//

#import "ReactionViewController.h"

@interface ReactionViewController ()<BluetoothUtilsDelegate,UIActionSheetDelegate>
{
    NSString    *recvText;
    unsigned long recvBytes;
    unsigned long sendBytes;
}
@property (weak, nonatomic) IBOutlet UIView *bodyView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (assign, nonatomic) NSInteger time;

@end

@implementation ReactionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _mBluetoothUtils = [[BluetoothUtils alloc]init];
    
    [_mBluetoothUtils initBLE];
    
    _mBluetoothUtils.delegate = self;
    
    recvText = [[NSString alloc]init];
    
    recvBytes = 0;
    sendBytes = 0;
    [_scanBtn addTarget:self action:@selector(scanDev) forControlEvents:UIControlEventTouchUpInside];
    [_startBtn setShowsTouchWhenHighlighted:NO];
    NSMutableArray *timeArray = [NSMutableArray array];
    for (ExperimentModel *model in self.dataArray) {
        if (model.timeModel) {
            [timeArray addObject:[NSString stringWithFormat:@"%ld",model.timeModel.allTime]];
        }
        else {
            if (model.time && ![model.time isEqualToString:@""]) {
                [timeArray addObject:model.time];
            }
        }
    }
    for (NSString *str in timeArray) {
        _time += [str integerValue] * 60;
    }
    NSLog(@"总时间:%ld",_time);
    
    
}
- (IBAction)endBtnClicked:(id)sender {
    POPBasicAnimation *anima = [POPBasicAnimation animation];
    [anima pop_removeAnimationForKey:@"countDown"];
}

- (IBAction)startBtnClicked:(id)sender {
    
    __weak typeof(self) ws = self;
    [UIView animateWithDuration:1.0 animations:^{
        __strong typeof(ws) strongSelf = ws;
        strongSelf.startBtn.alpha = 0;
    } completion:^(BOOL finished) {
        __strong typeof(ws) strongSelf = ws;
        strongSelf.startBtn.hidden = YES;
        strongSelf.timeLabel.hidden = NO;
        strongSelf.timeLabel.alpha = 1.0;
    }];
    [self setupCountDown];
    [self SendData];
}

- (void)setupCountDown {
    POPAnimatableProperty *pop = [POPAnimatableProperty propertyWithName:@"countDown" initializer:^(POPMutableAnimatableProperty *prop) {
        prop.writeBlock = ^(id obj, const CGFloat *values) {
            UILabel *lable = (UILabel*)obj;
            lable.text = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d",((int)values[0]/60)/60,(int)values[0]/60%60,(int)values[0]%60,(int)(values[0]*100)%60];
            NSLog(@"values:%f",values[0]);
        };
    }];
    POPBasicAnimation *anBasic = [POPBasicAnimation linearAnimation];
    anBasic.property = pop;
    anBasic.fromValue = @(self.time);
    anBasic.toValue = @(0);
    anBasic.duration = self.time;
    anBasic.beginTime = CACurrentMediaTime() + 1.0f;
    [_timeLabel pop_addAnimation:anBasic forKey:@"countDown"];
}

#pragma BluetoothUtils Delegate
- (void)ScanCompleteNotify{
    
    UIActionSheet *portsList = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancle" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    for (int i=0;i<_mBluetoothUtils.peripherals.count;i++)
    {
        CBPeripheral *peripheral = _mBluetoothUtils.peripherals[i];
        int rssi = [_mBluetoothUtils.devRssi[i] intValue];
        NSString *string = [NSString stringWithFormat:@"%@,RSSI=%d",peripheral.name,rssi];
        [portsList addButtonWithTitle: string];
    }
    [portsList showInView:self.view];
}

- (void)CharacterDiscCompleteNotify{
    [_mBluetoothUtils notification:0xfee0 characteristicUUID:0xfee1 p:_mBluetoothUtils.activePeripheral on:YES];
    [_scanBtn setTitle:@"Disconnect" forState:UIControlStateNormal];
    [_scanBtn addTarget:_mBluetoothUtils action:@selector(disConnectPeripheral:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)ConnectCompleteNotify{
    
}

- (void)DisconnectNotify{
    [_scanBtn setTitle:@"Scan BLE Device" forState:UIControlStateNormal];
    [_scanBtn addTarget:self action:@selector(scanDev) forControlEvents:UIControlEventTouchDown];
}

- (void)scanDev{
    [_mBluetoothUtils beginScan:3 withServiceUUID:@[[CBUUID UUIDWithString:@"FEE0"]]];
    // [mBluetoothUtils beginScan:10 withServiceUUID:nil];
}

- (void)SendData{
    
    NSString *str = [[NSString alloc]initWithFormat:@"%@",_ReactionStr];
    if ([_asiicHexBtn.titleLabel.text isEqualToString:@"Ascii"])
    {
        sendBytes += str.length;
        NSData *data = [str dataUsingEncoding: NSUTF8StringEncoding];
        [_mBluetoothUtils writeValue:0xfee0 characteristicUUID:0xfee1 p:_mBluetoothUtils.activePeripheral data:data];
    }
    else
    {
        sendBytes += str.length/2;
        NSData *data = [[NSData alloc]initWithData:[self stringToHexData:str]];
        [_mBluetoothUtils writeValue:0xfee0 characteristicUUID:0xfee1 p:_mBluetoothUtils.activePeripheral data:data];
    }
    
}

#pragma ActionSheet Delegate
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex!=0) {
        CBPeripheral *p = _mBluetoothUtils.peripherals[buttonIndex-1];
        _BLEName.text = p.name;
        [_mBluetoothUtils connectPeripheral:p];
    }
}

#pragma mark - 数据传输处理
-(unsigned char)Hex:(unsigned char)value{
    unsigned char tH = value;
    unsigned char vH;
    if (tH >= '0' && tH <= '9') {
        vH = tH - '0';
    }else if (tH >= 'a' && tH <= 'f'){
        vH = tH - 'a' + 10;
    }else {
        vH = tH - 'A' + 10;
    }
    
    return vH;
}

-(unsigned char)getHex:(unsigned char[2])value{
    unsigned char tH = value[0],tL = value[1];
    unsigned char vH,vL;
    if (tH >= '0' && tH <= '9') {
        vH = tH - '0';
    }else if (tH >= 'a' && tH <= 'f'){
        vH = tH - 'a' + 10;
    }else {
        vH = tH - 'A' + 10;
    }
    
    if (tL >= '0' && tL <= '9') {
        vL = tL - '0';
    }else if (tL >= 'a' && tL <= 'f'){
        vL = tL - 'a' + 10;
    }else {
        vL = tL - 'A' + 10;
    }
    
    unsigned char h = vH<<4,l = vL;
    unsigned char rV = h|l;
    return rV;
}

-(NSData *)stringToHexData:(NSString *)string{
    NSMutableData *returnData = [[NSMutableData alloc] init];
    const char *temp = [string UTF8String];
    unsigned long len = strlen(temp);
    for (int i = 0; i < len; i+=2) {
        unsigned char doubleChar[2];
        if (i<len) {
            doubleChar[0] = temp[i];
        }
        if (i+1<len) {
            doubleChar[1] = temp[i+1];
        }
        
        unsigned char temp = [self getHex:doubleChar];
        [returnData appendData:[NSData dataWithBytes:&temp length:1]];
    }
    return [NSData dataWithData:returnData];
}
@end
